package com.dummy.file;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DummyFileActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */

	//Declare global vars
	Button enter, retrieve;
	EditText outputname, outputtext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//Setup widgets
		enter = (Button) findViewById(R.id.button1);
		enter.setOnClickListener(this);
		enter.setText("Enter");
		retrieve = (Button) findViewById(R.id.button2);
		retrieve.setOnClickListener(this);
		retrieve.setText("Retrieve");
		outputname = (EditText) findViewById(R.id.editText1);
		outputtext = (EditText) findViewById(R.id.editText2);
		TextView name = (TextView) findViewById(R.id.textView1);
		name.setText("File Name");
		TextView body = (TextView) findViewById(R.id.textView2);
		body.setText("File Content");
	}
	public void onClick(View v) {
		//create file
		if(v.equals(enter))
		{
			try {
				OutputStreamWriter out = new OutputStreamWriter(openFileOutput(outputname.getText().toString(), Context.MODE_WORLD_READABLE));
				out.write(outputtext.getText().toString());
				out.close();
				Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//show file text
		else if(v.equals(retrieve))
		{
			//open file
			InputStream in = null;
			try {
				in = openFileInput(outputname.getText().toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			//read text off file
			if(in != null)
			{
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String str, text = "";
				try {
					while((str = reader.readLine()) != null)
					{
						text += str;
					}
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				//display text
				Toast.makeText(this, text, Toast.LENGTH_LONG).show();
			}
		}
	}
}